package fct.mpc.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.hardware.SensorListener;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.ViewGroup;

@SuppressWarnings("deprecation")
public class RotateView extends ViewGroup implements SensorListener, LocationListener
{
	private Canvas rotateCanvas = new Canvas();
	private float heading = 0;
	
	public RotateView(Context context)
	{
		super(context);
	}

	@Override
	protected void dispatchDraw(Canvas canvas)
	{
		canvas.save(Canvas.MATRIX_SAVE_FLAG);
		canvas.rotate(-heading, getWidth() * 0.5f, getHeight() * 0.5f);
		
		rotateCanvas = canvas;
		
		super.dispatchDraw(rotateCanvas);
		
		canvas.restore();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		int w = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
		int h = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
		int sizeSpec;

		if (w > h)
			sizeSpec = MeasureSpec.makeMeasureSpec((int) (w * Math.sqrt(2)), MeasureSpec.EXACTLY);
		else
			sizeSpec = MeasureSpec.makeMeasureSpec((int) (h * Math.sqrt(2)), MeasureSpec.EXACTLY);

		int child = getChildCount();
		for (int i = 0; i < child; i++)
			getChildAt(i).measure(sizeSpec, sizeSpec);
		
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b)
	{
		int width = getWidth();
		int height = getHeight();
		int child = getChildCount();
		
		for (int i = 0; i < child; i++)
		{
			View view = getChildAt(i);
			
			int childWidth = view.getMeasuredWidth();
			int childHeight = view.getMeasuredHeight();
			int childLeft = (width - childWidth) / 2;
			int childTop = (height - childHeight) / 2;
			
			view.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
        }
	}
//	@Override
	public void onAccuracyChanged(int sensor, int accuracy)
	{
	}

//	@Override
	public void onSensorChanged(int sensor, float[] values)
	{
		synchronized (this)
		{
			heading = values[3];
			invalidate();
		}	
	}

//	@Override
	public void onLocationChanged(Location location)
	{
		if(HuntingGrounds.nearSnipe(location))
		{
			Vibrator vibration = (Vibrator)getContext().getSystemService(Activity.VIBRATOR_SERVICE);
			vibration.vibrate(2000);
			// enters capture mode!!!
		}
	}

//	@Override
	public void onProviderDisabled(String provider)
	{
	}

//	@Override
	public void onProviderEnabled(String provider)
	{
	}

//	@Override
	public void onStatusChanged(String provider, int status, Bundle extras)
	{
	}
}
